﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;
using LIMIS.Filters;
using LIMIS.Models;
using System.Globalization;

namespace LIMIS.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login()
        {
            return View();
        }

        //
        // POST: /Account/Login

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                return RedirectToAction("Index", "Home");
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ModelState.AddModelError("", "用户名或密码错误。");
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            WebSecurity.Logout();

            return RedirectToAction("Index", "Home");
        }

        //
        // POST: /Account/ManageRoles

        public ActionResult ManageRoles()
        {
            var roles = Roles.GetAllRoles();

            return View(roles);
        }

        //
        // POST: /Account/AddOrEditRole

        [HttpPost]
        public ActionResult AddOrEditRole(string newrolename, string oldrolename)
        {
            if (!string.IsNullOrEmpty(oldrolename)&&Roles.RoleExists(oldrolename))
            {
                string[] users = Roles.GetUsersInRole(oldrolename);
                Roles.CreateRole(newrolename);
                if (users.Length > 0)
                {
                    Roles.AddUsersToRole(users, newrolename);
                    Roles.RemoveUsersFromRole(users, oldrolename);
                }
                Roles.DeleteRole(oldrolename);
            }
            else if(oldrolename!=newrolename)
            {
                Roles.CreateRole(newrolename);
            }
            var roles = Roles.GetAllRoles();
            return View("ManageRoles", roles);
        }

        //
        // Get: /Account/DeleteRole

        [HttpGet]
        public ActionResult DeleteRole(string rolename)
        {
            if (string.IsNullOrEmpty(rolename)|| !Roles.RoleExists(rolename))
            {
                ModelState.AddModelError("DeleteRole", "角色名称错误！");                
            }
            else
            {
                string[] users = Roles.GetUsersInRole(rolename);
                if (users.Length > 0)
                {
                    ModelState.AddModelError("DeleteRole", "此角色下存在用户不能删除！");
                }
                else {
                    Roles.DeleteRole(rolename);
                }                
            }
            var roles = Roles.GetAllRoles();
            return View("ManageRoles", roles);
        }

        //
        // POST: /Account/UserToRole

        [HttpPost]
        public ActionResult UserToRole(string rolename, string username, bool? ischecked)
        {
            if (ischecked.HasValue && ischecked.Value)
            {
                Roles.AddUserToRole(username, rolename);
            }
            else
            {
                Roles.RemoveUserFromRole(username, rolename);
            }

            return RedirectToAction("Users");
        }

        //
        // GET: /Account/ManageUsers

        public ActionResult ManageUsers()
        {
            IEnumerable<UserProfile> users;
            using (LIMISDbContext db = new LIMISDbContext())
            {
                users = db.UserProfiles.ToList();
            }

            ViewBag.Roles = Roles.GetAllRoles();
            
            return View(users);
        }

        //
        // GET: /Account/AddUser

        public ActionResult AddUser()
        {
            return View();
        }

        //
        // POST: /Account/AddUser

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult AddUser(AddModel model)
        {
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                try
                {
                    if (!WebSecurity.UserExists(model.UserName))
                    {
                        ModelState.AddModelError("", "用户名已存在，请重新输入！");
                        return View(model);
                    }
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                    WebSecurity.Login(model.UserName, model.Password);
                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        public JsonResult IsUserNameAvailable(string UserName)
        {

            if (!WebSecurity.UserExists(UserName))
                return Json(true, JsonRequestBehavior.AllowGet);

            string suggestedUserName = String.Format(CultureInfo.InvariantCulture,
                "此用户名已存在！", UserName);
           
            return Json(suggestedUserName, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Account/ChangePassword

        public ActionResult ChangePassword(ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "已更改您的密码！" : "";
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(LocalPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // 在某些失败方案中，ChangePassword 将引发异常，而不是返回 false。
                bool changePasswordSucceeded;
                try
                {
                    changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePassword", new { Message = ManageMessageId.ChangePasswordSuccess });
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }


        #region 帮助程序
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入其他用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入其他电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion
    }
}
